﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.BL;
using OBUCare.Core.Common;
using System.IO;
//using AutoMapper;


namespace OBUCare.Web.Controllers
{
    public class TransferController : Controller
    {
        private OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        UserMgr uMgr = new UserMgr();
        ConfigMgr configMgr = new ConfigMgr();

        public ActionResult ParentPage()
        {
            return View();
        }
        #region 交接单管理首页

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult Delete(long id, string sql, string searchSql)
        {
            //var list = db.TRANSFER_BILL_DETAIL.ToList().Where(c=>c.TRANSAFER_BILL_ID==id);
            //foreach (var item in list)
            //{
            //    db.TRANSFER_BILL_DETAIL.Remove(item);
            //}
            //var transfer = db.TRANSFER_BILLS.Find(id);
            //db.TRANSFER_BILLS.Remove(transfer);
            //db.SaveChanges();
            //var result = getTransferBills(null);
            //var temp = new GridModel(result);
            //return View(temp);

            //obuMgr.CancelTransferBills(new long[] { id }, UIUtility.GetCurrentUser());
            //View();
            //return this.ListTransferBillSqlItems(sql, searchSql);
            return View();
        }



        /// <summary>
        /// 检查交接单中的维修单是否有进入下一流程
        /// </summary>
        /// <param name="id">交接单id</param>
        /// <returns></returns>
        public bool CheckTransfer(long id)
        {
            bool flag = true;
            var transfer_model=(from g in db.TRANSFER_BILLS 
                               where g.ID==id select g).FirstOrDefault();
            var transfer_type=transfer_model.TRANSFER_TYPE;
            var transfer_status=transfer_model.STATUS;

            TransferType transferType = (TransferType)transfer_type;

            var transfer=(from i in db.TRANSFER_BILL_DETAIL
                          where i.TRANSAFER_BILL_ID==id 
                          select i.REPAIR_ORDER_ID).ToArray();
            var repairOrders=(from r in db.REPAIR_ORDERS
                             where transfer.Contains(r.ID)
                             select r.STATUS).ToArray();
            var checkStatus=repairOrders.Distinct();

            if(checkStatus.Count()>1)
            {
                flag= false;            
            }
            else if (checkStatus.Count() == 1)
            {
                switch (transferType)
                {
                    case TransferType.AgentToRepairCenter://营业厅--维修组
                        {
                            if (transfer_status == 1)
                            {
                                if (RepairOrderStatus.ReadyForReturnToSupplier.ToInt() < checkStatus.FirstOrDefault())
                                    flag = false;
                            }
                            else
                            {
                                if (RepairOrderStatus.ReturnedToRepairGroup.ToInt() < checkStatus.FirstOrDefault())
                                    flag = false;
                            }
                        }
                        break;
                    case TransferType.RepairCenterToSupplier://维修组--厂商
                        {
                            if (RepairOrderStatus.ReturnedToSupplier.ToInt() < checkStatus.FirstOrDefault())
                                flag= false;
                        }
                        break;
                    case TransferType.SupplierToRepairCenter://厂商--维修组
                        {
                            if (RepairOrderStatus.RepairedAndReturnedToRepariGroup.ToInt() < checkStatus.FirstOrDefault())
                                flag= false;
                        }
                        break;
                    case TransferType.RepairCenterToAgent://维修组--营业厅
                        {
                            if (transfer_status == 1)
                            {
                                if (RepairOrderStatus.ReadyForInformCustomer.ToInt() < checkStatus.FirstOrDefault())
                                    flag = false;
                            }
                            else
                            {
                                if (RepairOrderStatus.RepairedAndReturnedToAgent.ToInt() < checkStatus.FirstOrDefault())
                                    flag = false;
                            }
                        }
                        break;
                }
            }
            else
            {
                flag= true;
            }
            return flag;
        }

        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult deleteTranfer(long ID, string agentNO, string Remark)
        {
            try
            {
                var v = db.TRANSFER_BILLS.Find(ID);
                if (agentNO != "" && v.TRANSFER_TYPE != TransferType.AgentToRepairCenter.ToInt() && v.STATUS == TransferStatus.Confirmed.ToInt())
                {
                    return Json(new { Success = false, ErrorMsg = "该交接单已确认或交接单方向不涉及本营业厅，无操作权限" });
                }
                else if (!CheckTransfer(ID))
                {
                    return Json(new { Success = false, ErrorMsg = "该交接单有维修单已经进入下一流程，不允许作废" });
                }
                else
                {
                    obuMgr.CancelTransferBills(new long[] { ID }, UIUtility.GetCurrentUser(), Remark);
                    return Json(new { Success = true, ErrorMsg = "" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, ErrorMsg = ex.Message });
            }
        }

        #endregion


        #region 交接单详情列表相关代码

        [HttpPost]
        public ActionResult CreateTransfer(string TransferType, string strIDs)
        {
            var ids = strIDs.Split(',').ToList();
            try
            {
                DealTransferType(TransferType, ids);
                return Content("<script>alert('生成交接单成功！');window.location='/Transfer/Index/'</script>");
            }
            catch (Exception ex)
            {
                return Content("<script>alert('生成交接单失败！</br>" + ex.Message + "');window.location='/Transfer/Index/'</script>");
            }

        }

        private void DealTransferType(string TransferType, List<string> ids)
        {
            List<long> sameSupIds = new List<long>();
            switch (TransferType)
            {
                case "1": //营业厅->维修组  
                    sameSupIds.Clear();
                    ids.Each(s =>
                    {
                        sameSupIds.Add(Convert.ToInt64(s.Substring(0, s.IndexOf('-'))));
                    });
                    CreateTransfer(TransferType, sameSupIds);
                    break;
                case "2": //维修组->厂商
                case "3": while (ids.Count != 0) //厂商->维修组  只要区分不同厂商即可 生成不同厂商的交接单
                    {
                        sameSupIds.Clear();
                        //string sup = ids[0].Substring(ids[0].IndexOf('-') + 1);
                        string sup = ids[0].Substring(ids[0].IndexOf('-') + 1, ids[0].IndexOf('*') - ids[0].IndexOf('-') - 1);
                        for (int i = ids.Count - 1; i >= 0; i--)
                        {
                            long id = Convert.ToInt64(ids[i].Substring(0, ids[i].IndexOf('-')));
                            //string supname = ids[0].Substring(ids[0].IndexOf('-') + 1, ids[0].Length - (ids[0].IndexOf('-') + 1) - 1);
                            string supname=ids[i].Substring(ids[i].IndexOf('-') + 1, ids[i].IndexOf('*') - ids[i].IndexOf('-') - 1);
                            if (sup == supname)
                            {
                                sameSupIds.Add(id);
                                ids.Remove(ids[i]);
                            }
                        }
                        CreateTransfer(TransferType, sameSupIds);
                    }
                    break;
                case "4": while (ids.Count != 0) //维修组->营业厅 只要区分营业厅即可
                    {
                        sameSupIds.Clear();
                        string agentName = ids[0].Substring(ids[0].IndexOf('*') + 1);
                        for (int i = ids.Count - 1; i >= 0; i--)
                        {
                            long id = Convert.ToInt64(ids[i].Substring(0, ids[i].IndexOf('-')));
                            string agent = ids[i].Substring(ids[i].IndexOf('*') + 1);
                            if (agentName == agent)
                            {
                                sameSupIds.Add(id);
                                ids.Remove(ids[i]);
                            }
                        }
                        CreateTransfer(TransferType, sameSupIds);
                    }
                    break;
            }
        }

        private void CreateTransfer(string TransferType, List<long> sameSupIds)
        {
            //保存备注与其对应的编号
            Dictionary<long, string> details = new Dictionary<long, string>();
            sameSupIds.Each(id =>
            {
                long longID = id.ToLong().Value;
                string comment = getTransferComments(longID);
                details.Add(longID, comment);
            });

            var u = UIUtility.GetCurrentUser();
            TRANSFER_BILLS transferBill = new TRANSFER_BILLS();
            transferBill.CONFIRM_DATE = DateTime.Now;
            transferBill.SEND_DATE = DateTime.Now;
            transferBill.TRANSFER_DATE = DateTime.Now;
            transferBill.CREATED_BY = u.OPERATOR_NAME;
            transferBill.CREATED_DATE = DateTime.Now;
            transferBill.OPERATOR_NO = u.OPERATOR_NO;
            transferBill.TRANSFER_TYPE = TransferType.ToInt().Value;

            //提交交接单
            var tID = obuMgr.Transfer(transferBill, details, u);
        }

        /// <summary>
        /// 列出待交接的维修单，为交接做准备
        /// </summary>
        /// <param name="strIDs"></param>
        /// <param name="TransferType"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PrepareTransfer(string strIDs, string TransferType)
        {
            //待交接维修单编号
            ViewBag.strIDs = strIDs;

            //交接类型
            ViewBag.TransferType = TransferType;

            //是否是预览模式
            ViewBag.IsPreView = false;

            //下一次操作的Action
            ViewBag.ActionName = "TransferConfirmed"; //"TransferPreview";

            //ajax查询数据时对应的action及参数
            ViewBag.SelectAction = "ListPrepareTransferBillDetails";
            ViewBag.SelectActionRouteValues = new { strIDs = strIDs };

            //获取交接单的标签
            var transferTypeInfo = configMgr.GetTypeValue(ConfigMgr.tblTransferBillType, TransferType.ToInt().ToText());
            if (transferTypeInfo != null)
            {
                ViewBag.Title = string.Format("电子标签维修维护交接单（{0}）", transferTypeInfo.DICT_TITLE);
            }

            var r = View("Transfer");

            return r;
        }

        /// <summary>
        /// 返回待交接维修单列表
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ListPrepareTransferBillDetails(string strIDs)
        {
            //var ids = strIDs.Split(',');
            //string str = string.Empty;
            //for (int i = 0; i < ids.Length; i++)
            //{
            //    str += ids[i].Substring(0, ids[i].IndexOf('-'));
            //}
            //var items = getTransferDetailsViewModel(str);
            var items = getTransferDetailsViewModel(strIDs);
            var temp = new GridModel(items);
            return View(temp);
        }


        /// <summary>
        /// 提交交接单到数据库
        /// </summary>
        /// <param name="transferBill"></param>
        /// <param name="strIDs"></param>
        /// <param name="TransferType"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult TransferConfirmed(TRANSFER_BILLS transferBill, string strIDs, TransferType TransferType/*, string OPERATOR_NO, DateTime? TRANSFER_DATE, string SEND_PEOPLE, DateTime? SEND_DATE, string RECEIVE_OPERATOR_NO, DateTime? CONFIRM_DATE*/)
        {
            try
            {
                var ids = strIDs.Split(',');

                //保存备注与其对应的编号
                Dictionary<long, string> details = new Dictionary<long, string>();
                ids.Each(id =>
                {
                    long longID = id.ToLong().Value;
                    string comment = getTransferComments(longID);
                    details.Add(longID, comment);
                });

                var u = UIUtility.GetCurrentUser();

                transferBill.TRANSFER_TYPE = TransferType.ToInt().Value;

                //提交交接单
                var tID = obuMgr.Transfer(transferBill, details, u);

                if (tID.HasValue)
                {
                    ViewBag.IsPreView = true;
                    View_TRANSFER_BILL_Info info = obuMgr.GetTransferBillViewInfo(tID.Value);
                    var strPartialView = this.RenderPartialViewToString("_TransferBill", info);

                    return Json(new { success = true, message = "", Html = strPartialView });
                }
                else
                {
                    return Json(new { success = false, message = "未知错误", Html = "" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message, Html = "" });
            }
        }

        /// <summary>
        /// 确认接收前的预览，或预览详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ConfirmReceivedPreview(long id, string agentNo)
        {
            //交接单编号
            ViewBag.ID = id.ToText();

            ViewBag.Agent = Request["agentNo"] == null ? "" : Request["agentNo"].ToString();
            //是否是预览模式
            ViewBag.IsPreView = true;

            //下一次操作的Action
            ViewBag.ActionName = "ConfirmReceived"; //"TransferPreview";

            //ajax查询数据时对应的action及参数
            ViewBag.SelectAction = "ListTransferBillDetails";
            ViewBag.SelectActionRouteValues = new { id = id };

            //交接单信息
            var bill = obuMgr.GetTransferBillViewInfo(id);

            //获取交接单的标签
            ViewBag.Title = string.Format("电子标签维修维护交接单（{0}）", bill.TRANSFER_TYPE_Title);
            return View("Transfer", bill);
        }

        /// <summary>
        /// 返回交接维修单列表
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ListTransferBillDetails(long id)
        {
            var items = getTransferDetailsViewModel(id);
            var temp = new GridModel(items);
            return View(temp);
        }

        /// <summary>
        /// 确认接收
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ConfirmReceived(long id)
        {
            try
            {
                obuMgr.ConfirmReceived(id, UIUtility.GetCurrentUser());
                return Json(new { success = true, message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        public ActionResult ConfirmReceivedNew(long id)
        {
            try
            {
                obuMgr.ConfirmReceived(id, UIUtility.GetCurrentUser());
                return Content("<script>alert('接收成功！');window.location='/Transfer/Index/'</script>");
            }
            catch (Exception ex)
            {
                return Content("<script>alert('接收失败！</br>'" + ex.Message + ");window.location='/Transfer/Index/'</script>");
            }
        }
        #endregion


        /// <summary>
        /// 检查操作是否逆向
        /// </summary>
        /// <param name="TransferType"></param>
        /// <param name="itemIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public string checkIfValidOper(string TransferType, string itemIDs)
        {
            return "";

            //检查流程是否逆向
            var id = itemIDs.Split(',');
            var a = db.REPAIR_ORDERS.Find(int.Parse(id[0]));
            if (int.Parse(a.STATUS.ToString()) >= TransferType.ToInt())
                return "系统不允许逆向操作！";
            else
                return "";
        }

        //填完交接信息的预览页面，已经将其取消
        //[HttpPost]
        //public ActionResult TransferPreview(TransferBillViewModel TransferBill, string strIDs, TransferType TransferType/*, string OPERATOR_NO, DateTime? TRANSFER_DATE, string SEND_PEOPLE, DateTime? SEND_DATE, string RECEIVE_OPERATOR_NO, DateTime? CONFIRM_DATE*/)
        //{
        //    ViewBag.strIDs = strIDs;
        //    ViewBag.TransferType = TransferType.ToString();
        //    ViewBag.IsPreView = true;
        //    ViewBag.TransferBill = TransferBill;

        //    var items = getTransferDetailsViewModel(strIDs).ToList();



        //    items.Each(item =>
        //    {
        //        item.REMARK = getTransferComments(item.ID);
        //    });

        //    ViewBag.ActionName = "TransferConfirmed";

        //    return View("Transfer", items);
        //}

        /// <summary>
        /// 从表单中取出对应的备注
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string getTransferComments(long id)
        {
            var temp = "";
            string key = "remark" + id.ToString();
            if (Request.Form.AllKeys.Contains(key))
                temp = this.Request.Form[key];
            return temp;
        }


        /// <summary>
        /// 获取待交接的维修单
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        private IEnumerable<TransferBillDetailViewModel> getTransferDetailsViewModel(string strIDs)
        {
            IList<TransferBillDetailViewModel> result = new List<TransferBillDetailViewModel>();

            if (!strIDs.IsNullOrEmpty())
            {
                string sqlWhere = string.Format(" ID in ({0})", strIDs);

                //查询待交接的维修单信息
                var items = obuMgr.GetRepairOrders(sqlWhere).ToList();
                AutoMapper.Mapper.CreateMap<View_RepariOrders, TransferBillDetailViewModel>().ForMember(t => t.TRANSAFER_BILL_ID, o => o.Ignore()).ForMember(t => t.REMARK, o => o.Ignore());
                items.Each(i =>
                {
                    var temp = AutoMapper.Mapper.Map<View_RepariOrders, TransferBillDetailViewModel>(i);
                    result.Add(temp);
                });
            }

            return result;
        }

        /// <summary>
        /// 查询交接单包含的维修单列表
        /// </summary>
        /// <param name="TRANSAFER_BILL_ID"></param>
        /// <returns></returns>
        private IEnumerable<TransferBillDetailViewModel> getTransferDetailsViewModel(long TRANSAFER_BILL_ID)
        {
            string sql = @"SELECT o.[ID]
	  ,[REPAIR_ORDER_NO]
	  ,[OBU_NO]
	  ,[USER_NO]
	  ,[USER_NAME]
	  ,[SUPPLIER]
	  ,[SPEC_NAME]
	  ,[REGISTER_DATE]
	  ,[REPORTER]
	  ,[TEL_NO]
	  ,[MOBILE_TEL_NO]
	  ,[MAX_PRICE]
	  ,[AGENT_NO]
	  ,[AGENT_NAME]
	  ,[CLIENT_IP]
	  ,[FACE_STATUS]
	  ,[FACE_STATUSTitle]
	  ,[REPAIR_TYPE]
	  ,[REPAIR_TYPE_Title]
	  ,[REPAIRED_COMMENT]
	  ,[IS_FREE]
	  ,[IsFreeTitle]
	  ,[IsNeedSPARE_OBU]
	  ,[SPARE_OBU_NO]
	  ,[SPARE_OBU_PRICE]
	  ,[SPARE_OBU_ISSUE_DATE]
	  ,[STATUS]
	  ,[StatusTitle]
	  ,[CURRENT_HANDLER]
	  ,[CONFIRM_REPAIRED]
	  ,[CONFIRM_REPAIRED_Title]
	  ,[DISPOSE_TYPE]
	  ,[DISPOSE_TYPE_Title]
	  ,[FINISHED_DATE]
	  ,[GET_BACK_DATE]
	  ,[IS_RETURNED_SPARE_OBU]
	  ,[IS_RETURNED_SPARE_OBU_Title]
	  ,[RETURNED_COMMENT]
	  ,[CREATED_BY]
	  ,[CreatedByName]
	  ,[CREATED_DATE]
	  ,[MODIFY_BY]
	  ,[ModifyByName]
	  ,[MODIFY_DATE]
	  ,[SUPPLIER_ShortName]
	  ,[VEHICLE_PLATE_NO]
	  ,td.REMARK
	  ,td.TRANSAFER_BILL_ID
  FROM TRANSFER_BILL_DETAIL td
	INNER join [View_RepariOrders] o on td.REPAIR_ORDER_ID=o.ID";

            sql = string.Format(sql + " where TRANSAFER_BILL_ID={0}", TRANSAFER_BILL_ID);

            //查询维修单信息
            var items = db.Database.SqlQuery<TransferBillDetailViewModel>(sql);

            return items;
        }



        #region 导出交接单详情的Excel，以便打印
        public ActionResult Export(string exportID)
        {
            string exportFileTitle = "交接单.xls";
            ActionResult result = null;
            try
            {
                long? logid = exportID.ToLong();
                if (logid.HasValue)
                {
                    string template = "";
                    ExportHelper export = null;
                    var u = UIUtility.GetCurrentUser();


                    //交接单信息
                    var bill = obuMgr.GetTransferBillViewInfo(logid.Value);
                    var items = getTransferDetailsViewModel(logid.Value);



                    if (items != null && items.Count() > 0)
                    {
                        #region 营业厅->维修组 维修组->营业厅
                        //如果是与营业厅交接
                        if (TransferType.AgentToRepairCenter.ToInt().Equals(bill.TRANSFER_TYPE) || TransferType.RepairCenterToAgent.ToInt().Equals(bill.TRANSFER_TYPE))
                        {
                            template = this.GetTemplateFilePath("交接单打印模板-营业厅.xls");
                            export = new ExportHelper(template);

                            int startRowIndex = 4;
                            int sheetIndex = 0;
                            int index = 1;

                            //将合计行往后移动数据总行数一1,同时输出营业厅和打印日期
                            export.ExportAddionalInfomation((excel, ep) =>
                            {
                                switch (bill.TRANSFER_TYPE)
                                {
                                    case (int)TransferType.AgentToRepairCenter:
                                        excel[0, 0] = "KTKF-F-J032";
                                        excel[3, 5] = "可接受费用";
                                        excel[1, 0] = "电子标签维修维护交接单(营业厅->维修组)";
                                        break;
                                    case (int)TransferType.RepairCenterToAgent:
                                        excel[0, 0] = "KTKF-F-J034";
                                        excel[3, 5] = "速通报价";
                                        excel[1, 0] = "电子标签维修维护交接单(维修组->营业厅)";
                                        break;
                                    default:
                                        excel[0, 0] = "KTKF-F-J032";
                                        excel[3, 5] = "可接受费用";
                                        excel[1, 0] = "电子标签维修维护交接单(营业厅->维修组)";
                                        break;
                                }
                                excel.ActiveSheetIndex = sheetIndex;
                                excel.ShiftRows(5, 8, items.Count() - 1);

                                //营业厅
                                excel[2, 1] = items.First().AGENT_NAME;

                                //交接单号
                                excel[2, 2] = "交接单号：";

                                excel[2, 3] = bill.TRANSFER_BILL_NO;

                                //日期
                                excel[2, 6] = DateTime.Now.ToString(UIConstants.DateFormatString);

                            });

                            if (bill.TRANSFER_TYPE == TransferType.AgentToRepairCenter.ToInt())
                            {  //如果是营业厅->维修组 则导出结果包含可接受费用
                                //导出主要数据
                                export.ExportToExcel(items, (item, excel, rowIndex) =>
                                {
                                    int colIndex = 0;

                                    excel[rowIndex, colIndex++] = (index++).ToString();
                                    excel[rowIndex, colIndex++] = item.REPAIR_ORDER_NO;
                                    excel[rowIndex, colIndex++] = item.OBU_NO;
                                    excel[rowIndex, colIndex++] = item.SUPPLIER_ShortName;
                                    excel[rowIndex, colIndex++] = item.SPEC_NAME;
                                    excel.SetCellValue(rowIndex, colIndex++, item.MAX_PRICE);
                                    excel[rowIndex, colIndex++] = item.REMARK;


                                    //设置样式
                                    for (int c = 0; c < colIndex; c++)
                                    {
                                        excel.SetCellStyle(startRowIndex, c, rowIndex, c);
                                    }

                                }, sheetIndex, startRowIndex);

                            }
                            else
                            { //如果是维修组->营业厅 则导出内容为 速通报价
                                //导出主要数据
                                export.ExportToExcel(items, (item, excel, rowIndex) =>
                                {
                                    int colIndex = 0;

                                    //获取厂商成本报价
                                    var orderPrice = (from i in db.REPAIR_ORDER_PRICE.ToList()
                                                      where i.REPAIR_ORDER_ID == item.ID && i.PRICE_FLAG != ConfigMgr.PriceFlag_Invalid
                                                      select i).ToList();
                                    decimal sumPrice = 0;
                                    if (orderPrice != null && orderPrice.Count > 0)
                                    {
                                        orderPrice.Each(o =>
                                        {
                                            sumPrice += o.PRICE;
                                        });
                                    }

                                    excel[rowIndex, colIndex++] = (index++).ToString();
                                    excel[rowIndex, colIndex++] = item.REPAIR_ORDER_NO;
                                    excel[rowIndex, colIndex++] = item.OBU_NO;
                                    excel[rowIndex, colIndex++] = item.SUPPLIER_ShortName;
                                    excel[rowIndex, colIndex++] = item.SPEC_NAME;
                                    excel.SetCellValue(rowIndex, colIndex++, sumPrice);
                                    excel[rowIndex, colIndex++] = item.REMARK;


                                    //设置样式
                                    for (int c = 0; c < colIndex; c++)
                                    {
                                        excel.SetCellStyle(startRowIndex, c, rowIndex, c);
                                    }

                                }, sheetIndex, startRowIndex);

                            }

                        }
                        #endregion
                        #region 厂商->维修组
                        else if (TransferType.SupplierToRepairCenter.ToInt().Equals(bill.TRANSFER_TYPE))
                        {
                            template = this.GetTemplateFilePath("交接单打印模板-厂商.xls");
                            export = new ExportHelper(template);

                            int startRowIndex = 3;
                            int sheetIndex = 0;
                            int index = 1;

                            //将合计行往后移动数据总行数一1,同时输出营业厅和打印日期
                            export.ExportAddionalInfomation((excel, ep) =>
                            {

                                excel[0, 0] = "电子标签维修维护交接单(厂商->维修组)";


                                excel.ActiveSheetIndex = sheetIndex;
                                excel.ShiftRows(5, 7, items.Count() - 1);

                                //厂商
                                excel[1, 1] = items.First().SUPPLIER_ShortName;

                                //交接单号
                                excel[1, 2] = "交接单号：";

                                excel[1, 3] = bill.TRANSFER_BILL_NO;

                                //日期
                                excel[1, 5] = "日期：";
                                excel[1, 6] = DateTime.Now.ToString(UIConstants.DateFormatString);
                            });

                            //导出主要数据
                            export.ExportToExcel(items, (item, excel, rowIndex) =>
                            {
                                int colIndex = 0;

                                //获取厂商成本报价
                                var orderPrice = (from i in db.REPAIR_ORDER_PRICE.ToList()
                                                  where i.REPAIR_ORDER_ID == item.ID && i.PRICE_FLAG != ConfigMgr.PriceFlag_Invalid
                                                  select i).ToList();
                                decimal sumPrice = 0;
                                if (orderPrice != null && orderPrice.Count > 0)
                                {
                                    orderPrice.Each(o =>
                                    {
                                        sumPrice += o.SUPPLIER_PRICE;
                                    });
                                }

                                excel[rowIndex, colIndex++] = (index++).ToString();
                                excel[rowIndex, colIndex++] = item.REPAIR_ORDER_NO;
                                excel[rowIndex, colIndex++] = item.OBU_NO;
                                excel[rowIndex, colIndex++] = item.SPEC_NAME;
                                excel.SetCellValue(rowIndex, colIndex++, sumPrice);
                                excel[rowIndex, colIndex++] = item.CONFIRM_REPAIRED_Title;
                                excel[rowIndex, colIndex++] = item.REMARK;


                                //设置样式
                                for (int c = 0; c < colIndex; c++)
                                {
                                    excel.SetCellStyle(startRowIndex, c, rowIndex, c);
                                }

                            }, sheetIndex, startRowIndex);
                        }
                        #endregion
                        #region 维修组->厂商
                        else //否则就是与厂商交接
                        {
                            template = this.GetTemplateFilePath("交接单打印模板-维修组.xls");
                            export = new ExportHelper(template);

                            int startRowIndex = 4;
                            int sheetIndex = 0;
                            int index = 1;

                            //将合计行往后移动数据总行数一1,同时输出营业厅和打印日期
                            export.ExportAddionalInfomation((excel, ep) =>
                            {
                                excel[0, 0] = "KTKF-F-J033";
                                excel[1, 0] = "电子标签维修维护交接单(维修组->厂商)";
                                excel.ActiveSheetIndex = sheetIndex;
                                excel.ShiftRows(5, 7, items.Count() - 1);

                                //厂商
                                excel[2, 1] = items.First().SUPPLIER_ShortName;

                                //交接单号
                                excel[2, 2] = "交接单号：";

                                excel[2, 3] = bill.TRANSFER_BILL_NO;

                                //日期
                                excel[2, 5] = DateTime.Now.ToString(UIConstants.DateFormatString);
                            });

                            //导出主要数据
                            export.ExportToExcel(items, (item, excel, rowIndex) =>
                            {
                                int colIndex = 0;

                                excel[rowIndex, colIndex++] = (index++).ToString();
                                excel[rowIndex, colIndex++] = item.REPAIR_ORDER_NO;
                                excel[rowIndex, colIndex++] = item.OBU_NO;
                                //excel[rowIndex, colIndex++] = item.SUPPLIER_ShortName;
                                excel[rowIndex, colIndex++] = item.SPEC_NAME;
                                excel.SetCellValue(rowIndex, colIndex++, item.MAX_PRICE);
                                excel[rowIndex, colIndex++] = item.REMARK;


                                //设置样式
                                for (int c = 0; c < colIndex; c++)
                                {
                                    excel.SetCellStyle(startRowIndex, c, rowIndex, c);
                                }

                            }, sheetIndex, startRowIndex);
                        }
                        result = export.DownLoad(this.File, exportFileTitle);
                    }
                        #endregion
                    else
                    {
                        return Content("<Script>alert('数据为空，打印失败!');window.location.href='/Transfer/Index/';</Script>");
                    }
                }
            }
            catch (Exception ex)
            {
                result = ExportHelper.HandleExportException(this, ex, exportFileTitle);
            }
            return result;
        }

        #endregion

        #region 查询交接单

        [HttpPost]
        public ActionResult Search(DateTime? FromCreatedDate, DateTime? ToCreatedDate,
            string Supplier, string TRANSFER_TYPE, string AgentType, string Agent,
            string TransferBillStatus
           )
        {
            try
            {

                //根据编号判断查询权限
                string whereAgentNo = Request["agentNO"] == null ? "" : Request["agentNO"].ToString();

                var sql = obuMgr.GetSearhTransferBillsSql(FromCreatedDate, ToCreatedDate, Supplier.ChangAllTextToNull(),
                    TRANSFER_TYPE.ChangAllTextToNull(), AgentType.ChangAllTextToNull(), Agent.ChangAllTextToNull(),
                    TransferBillStatus.ChangAllTextToNull(), whereAgentNo);

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }


        [GridAction]
        public ActionResult ListTransferBillSqlItems(string sql, string searchSql)
        {
            try
            {
                //根据编号判断查询权限
                string whereAgentNo = Request["AgentNo"] == null ? "" : Request["AgentNo"].ToString();

                whereAgentNo = whereAgentNo == "" ? "" : " AND (TRANSFER_FROM='" + whereAgentNo + "' OR TRANSFER_TO='" + whereAgentNo + "')";

                string tempSql = "";
                if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                    tempSql = sql + " and " + searchSql;
                else
                    tempSql = string.Format("{0} {1}", sql, searchSql);

                string normalSql = tempSql.Trim() == "" ?
        " CREATED_DATE>='" + DateTime.Now.ToShortDateString() + "' AND CREATED_DATE <'" + DateTime.Now.AddDays(1).ToShortDateString() + "' " :
        "";//如果没有任何条件 则默认显示当天的所有信息
                whereAgentNo = tempSql.Trim() == "" ? whereAgentNo : tempSql.Trim().Contains("TRANSFER_FROM") == true ? "" : whereAgentNo;//如果查询条件为空，则该默认条件有效，如果不为空，则该默认值为空

                var result = obuMgr.GetTransferBills(tempSql + normalSql + whereAgentNo).ToList();

                if (Request["AgentNo"] == null || Request["AgentNo"].ToString() == "")//如果是所有营业厅的权限  
                {
                    result.Each(r =>
                        {
                            //只确认接收 营业厅->维修组的交接单 
                            if (r.TRANSFER_TYPE == TransferType.AgentToRepairCenter.ToInt() && r.STATUS == TransferStatus.Normal.ToInt())
                                r.setConfirmShowTime("inline");
                            else
                                r.setConfirmShowTime("none");
                            // 不能作废营业厅->维修组的单子(正常)和维修组->营业厅(营业厅已确认接收)
                            if ((r.TRANSFER_TYPE == TransferType.AgentToRepairCenter.ToInt() && r.STATUS == TransferStatus.Normal.ToInt()) ||
                                (r.TRANSFER_TYPE == TransferType.RepairCenterToAgent.ToInt() && r.STATUS == TransferStatus.Confirmed.ToInt()) ||
                                r.STATUS == TransferStatus.Obsolete.ToInt())
                                r.setDeleteVisable("none");
                            else
                                r.setDeleteVisable("inline");
                        });
                }
                else //如果是本营业厅的权限
                {
                    result.Each(r =>
                    {
                        // 只接收 维修组->营业厅方向的正常的交接单
                        if (r.TRANSFER_TYPE == TransferType.RepairCenterToAgent.ToInt() && r.STATUS == TransferStatus.Normal.ToInt())
                            r.setConfirmShowTime("inline");
                        else
                            r.setConfirmShowTime("none");

                        //只能作废营业厅->维修组(正常)的单子
                        if (r.TRANSFER_TYPE == TransferType.AgentToRepairCenter.ToInt() && r.STATUS == TransferStatus.Normal.ToInt())
                            r.setDeleteVisable("inline");
                        else
                            r.setDeleteVisable("none");
                    });
                }
                var temp = new GridModel(result.OrderByDescending(t => t.CREATED_DATE));
                return View(temp);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        /// <summary>
        /// 根据维修单状态，返回维修单，为空则返回全部
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>     
        public ActionResult List(TransferType? id)
        {
            //记录当前默认筛选的状态
            ViewBag.TransferTypeS = id.HasValue ? id.ToInt().ToText() : UIConstants.AllItems;

            ViewBag.TransferStatus = id.HasValue ? TransferStatus.Normal.ToInt().ToText() : UIConstants.AllItems;
            // ViewData["SupplierShortName"] = new ObuDropDownListHlper().GetSuppliersShortName(UIConstants.AllItems, true, new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems));

            string sql = "";
            if (id.HasValue && id > 0)
            {
                sql = " TRANSFER_TYPE=" + id.ToInt().ToText() + " AND STATUS=" + TransferStatus.Normal.ToInt();
            }
            ViewBag.Sql = sql;
            return View("Index");
        }

        #endregion


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            obuMgr.Dispose();
            configMgr.Dispose();
            uMgr.Dispose();
            base.Dispose(disposing);
        }
    }
}
